package com.zhiwei.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhiwei.common.constant.HttpConstants;
import com.zhiwei.common.constant.ResultResponseMsg;
import com.zhiwei.common.service.GatewayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * function 网关服务实现类
 * author zhiwei.yang
 * time 2020-2-28-10:23
 */
@Service
public class GatewayServiceImpl implements GatewayService {

    /** 网关服务名 **/
    private final String GATEWAY_SERVICE_NAME = "publish-gateway";
    private final String GATEWAY_SERVICE_API = "http://" + GATEWAY_SERVICE_NAME + "/publish-gateway/gateway";

    //生产黄金Redis缓存
    private final Set<String> cacheWhiteSet = new ConcurrentSkipListSet<>();

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private PathMatcher pathMatcher;

    @Override
    public String checkToken(String token) {
        Map<String,String> requestMap = new HashMap<>();
        requestMap.put(HttpConstants.HEADER_TOKEN, token);
        String url = GATEWAY_SERVICE_API + "/token/check?token={token}";
        ResultResponseMsg resultResponseMsg = restTemplate.getForEntity(url, ResultResponseMsg.class,requestMap).getBody();
        return (String)resultResponseMsg.getData();
    }

    @Override
    public List<String> syncWhiteList() {
        String url = GATEWAY_SERVICE_API + "/whiteList";
        ResultResponseMsg resultResponseMsg = restTemplate.getForEntity(url, ResultResponseMsg.class).getBody();
        List<String> whiteList = JSON.parseArray(JSON.toJSONString(resultResponseMsg.getData()), String.class);
        cacheWhiteSet.addAll(whiteList);
        return whiteList;
    }

    @Override
    public synchronized boolean checkWhiteList(String requestUri) {
        if(CollectionUtils.isEmpty(cacheWhiteSet)){
            syncWhiteList();
        }
        for(String path : cacheWhiteSet){
            if(pathMatcher.match(path, requestUri)){
                return true;
            }
        }
        return false;
    }
}
